//current selected settings
var _appSetting;

function hasAppSetting(){
    return (localStorage['history'] && localStorage['config_name']);
}

function openOptionsPage(){
    var url  = chrome.extension.getURL('options.html?is_first=1');
    chrome.tabs.create({url:url});
}

function insertScript(name){
    if(hasAppSetting()){
        _appSetting = JSON.parse(localStorage["history"])[name]; 
        chrome.tabs.executeScript(null, {file:"contents/script.js", allFrames:true});
    }else{
        openOptionsPage(); 
    }
}

chrome.browserAction.onClicked.addListener(function(tab){
    var historyName = localStorage['config_name'];
    insertScript(historyName);
});

chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
    switch(request.type){
        case "getAppSetting":
            sendResponse({data:_appSetting});
            break;
        case "injectJS":
            var tab = sender.tab;
            chrome.tabs.executeScript(tab.id, {file:request.url});
            // console.log("injectJS", request.url);
            sendResponse({});
            break;
    }
});